package com.opennetexam.manager.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by admin on 2017/11/22.
 */
public class CommonUtil {

    /**
     * 正则校验
     * @param parameter  参数
     * @param reg  规则
     * @return
     */
    public static boolean matchesStr(String parameter,String reg){
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(parameter);
        return matcher.matches();
    }

    public static void strToByte(String parameter,HttpServletResponse response){
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(parameter);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void photoToByte(HttpServletResponse response){
        try {

            File file = new File("");
            String path = file.getCanonicalPath();

            Resource resource = new ClassPathResource("\\static\\App\\images\\Login\\defaultPhoto.jpg");
//            File file1 = new File(path+"\\manager\\build\\resources\\main\\static\\App\\images\\Login\\defaultPhoto.jpg");

//            System.out.println(file1.getCanonicalPath());

            //读取本地图片输入流
//            FileInputStream inputStream = new FileInputStream(file1.getCanonicalPath());
            InputStream inputStream = resource.getInputStream();
            int i = inputStream.available();
            //byte数组用于存放图片字节数据
            byte[] buff = new byte[i];
            inputStream.read(buff);
            //记得关闭输入流
            inputStream.close();
            //设置发送到客户端的响应内容类型
            response.setContentType("image/*");
            OutputStream out = response.getOutputStream();
            out.write(buff);
            //关闭响应输出流
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
